package com.lv.phuotbacnam.ui.fragment;

import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.internal.Logger;
import com.lv.phuotbacnam.R;
import com.lv.phuotbacnam.bl.callback.ThreadSafeResultCallback;
import com.lv.phuotbacnam.bl.network.error.ApplicationError;
import com.lv.phuotbacnam.bl.queries.QueriesConstant;
import com.lv.phuotbacnam.bl.queries.QueriesConstant.TableUser;
import com.lv.phuotbacnam.bl.utils.ImageLoaderCus;
import com.lv.phuotbacnam.bl.utils.IntentHelper;
import com.lv.phuotbacnam.toolbox.ImageUtils;
import com.lv.phuotbacnam.ui.Constants;
import com.lv.phuotbacnam.ui.activity.BaseActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.parse.SaveCallback;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class thongtincanhan extends BaseActivity implements Serializable {
	// private final int RESULT_LOAD_IMAGE = 12323;
	private static int RESULT_LOAD_IMAGE = 1;
	private ImageView currentExpectingImage;
	public ImageLoader imageLoader;
	public ImageLoader image;
	public String tendaydu = "";
	public String mail = "";
	public String diachi = "";
	public String dienthoai = "";
	public String ngaysinh = "";
	public String gioitinh = "";
	public int diem = 0;
	JSONArray jsonArrayBitmap = new JSONArray();
	Bitmap b;
	int numberBitmapSaved = 0;
	public static final String URL = "url";
	ParseUser user = (ParseUser) IntentHelper.getObjectForKey("user");

	
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.thongtincanhan);
		imageLoader = ImageLoader.getInstance();
		ImageView profileImage = (ImageView) findViewById(R.id.left_menu_pic);
		imageLoader.displayImage(user.getString(TableUser.COLUMN_photoURL),
				profileImage);
		/*
		 * event click image go to thongtincanhan class
		 */
		profileImage.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ParseUser user = ParseUser.getCurrentUser();
				Intent intent = new Intent(thongtincanhan.this,
						thongtincanhan.class);
				IntentHelper.addObjectForKey(user, "user");
				startActivity(intent);
				finish();
			}
		});
		/*
		 * set image profile and fullname
		 */
		TextView profileFullName = (TextView) findViewById(R.id.left_menu_fullname);
		profileFullName.setText(user.getString(TableUser.COLUMN_firstName)
				+ " " + user.getString(TableUser.COLUMN_lastName));
		
		final ImageView im = (ImageView) findViewById(R.id.anhbia);
		image = ImageLoader.getInstance();
		DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
				.cacheOnDisc(true).resetViewBeforeLoading(true).build();
//Initialize ImageLoader with configuration. Do it once.
image.init(ImageLoaderConfiguration.createDefault(getBaseContext()));
image.displayImage(user.getString(TableUser.COLUMN_anhbia),im,options);



		
		//image.displayImage(user.getString(TableUser.COLUMN_anhbia),im);
		
		/*
		 * / event click image background
		 */
		im.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (user == ParseUser.getCurrentUser()){
				currentExpectingImage = (ImageView) v;
				Intent i = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(i, RESULT_LOAD_IMAGE);
				if (b != null){
					 
					createImageParseFile(b);
					
					
					Log.i("info",URL);
					
					BitmapDrawable ob = new BitmapDrawable(b);
					im.setBackgroundDrawable(ob);
				}
				}
				//

			}
		});
		TextView txt_tendaydu = (TextView) findViewById(R.id.tendaydu_hienthi);
		TextView txt_mail = (TextView) findViewById(R.id.mail_hienthi);
		TextView txt_diachi = (TextView) findViewById(R.id.diachi_hienthi);
		TextView txt_dienthoai = (TextView) findViewById(R.id.dienthoai_hienthi);
		TextView txt_ngaysinh = (TextView) findViewById(R.id.ngaysinh_hienthi);
		TextView txt_gioitinh = (TextView) findViewById(R.id.gioitinh_hienthi);
		TextView txt_diem = (TextView) findViewById(R.id.diem_hienthi);
		Button btn_edit = (Button) findViewById(R.id.btn_edit);
		if (user==ParseUser.getCurrentUser()) btn_edit.setVisibility(View.VISIBLE);
		else btn_edit.setVisibility(View.GONE);

		// // set data to textviews
		tendaydu = user.getString(QueriesConstant.TableUser.COLUMN_firstName)
				+ " "
				+ user.getString(QueriesConstant.TableUser.COLUMN_lastName);
		txt_tendaydu.setText("Tên đầy đủ: " + tendaydu);
		mail = user.getString(QueriesConstant.TableUser.COLUMN_email);
		txt_mail.setText("Email: " + mail);

		diachi = user.getString(QueriesConstant.TableUser.COLUMN_dia_chi);
		txt_diachi.setText("Địa chỉ: " + diachi);

		dienthoai = user.getString(QueriesConstant.TableUser.COLUMN_phone);
		txt_dienthoai.setText("Số điện thoại: " + dienthoai);
		ngaysinh = user.getString(QueriesConstant.TableUser.COLUMN_ngaysinh);
		txt_ngaysinh.setText("Ngày sinh: " + ngaysinh);
		gioitinh = user.getString(QueriesConstant.TableUser.COLUMN_gioitinh);
		txt_gioitinh.setText("Giới tính: " + gioitinh);
		diem = user.getInt(QueriesConstant.TableUser.COLUMN_diem_tich_luy);
		txt_diem.setText("Điểm tích lũy: " + diem);

		btn_edit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(thongtincanhan.this, edit_ten.class);
				i.putExtra("tendaydu", tendaydu);
				i.putExtra("diachi", diachi);
				i.putExtra("dienthoai", dienthoai);
				i.putExtra("ngaysinh", ngaysinh);
				i.putExtra("gioitinh", gioitinh);
				startActivity(i);
				finish();
			}
		});
		
		
	}
	@Override
	protected void onRestart() {

	    // TODO Auto-generated method stub
	    super.onRestart();
	    Intent i = new Intent(thongtincanhan.this, thongtincanhan.class);  //your class
	    startActivity(i);
	    finish();

	}
	@Override
	protected void onStart() {
	    super.onStart();  // Always call the superclass method first	   
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		// Get the selected image
		if (requestCode == RESULT_LOAD_IMAGE
				&& resultCode == Activity.RESULT_OK && null != data) {
			ImageUtils.decodeFromUri(
					thongtincanhan.this,
					data.getData(),
					new ThreadSafeResultCallback<Object, Bitmap>(Looper
							.getMainLooper()) {

						@Override
						public void doOnSuccess(Object request, Bitmap result) {
							/* show current expecting image to image view */
							currentExpectingImage.setImageBitmap(result);

							/* add bitmap to array list */
							b = result;
						}

						@Override
						public void doOnError(ApplicationError error) {
						}
					});
		}
	}
	public void createImageParseFile(Bitmap bm) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
		final ParseFile pFile = new ParseFile("file", stream.toByteArray());
		pFile.saveInBackground(new SaveCallback() {
			@Override
			public void done(ParseException arg0) {
				try {
					JSONObject anImageObjec = new JSONObject();
					anImageObjec.put(URL, pFile.getUrl());
					
					// anImageObjec.put(NAME, pFile.getName());
					// anImageObjec.put(TYPE, "File");
					jsonArrayBitmap.put(anImageObjec);
					Log.i("info",pFile.getUrl().toString());
					user.put(QueriesConstant.TableUser.COLUMN_anhbia, pFile.getUrl().toString());
					user.saveInBackground();
				} catch (Exception e2) {
					Logger.registerAccessToken("createImageParseFile Error");
				}
				numberBitmapSaved += 1;
			}
		});
	}

	@Override
	protected int getContainerId() {
		// TODO Auto-generated method stub
		return 0;
	}


}
